#!/bin/bash

PGNAME=`basename $0`
PGDIRNAME=`dirname $0`
PGERR="$PGNAME[$$]: "

if [ -z "${MLPROD_HOME}" ]
then
  echo "${PGERR} :  MLPROD_HOME env not set;  exiting !!!" >&2
  exit 10
fi

PGCFG_FILE="${MLPROD_HOME}/config/mlprog.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!" >&2
  exit 10
fi

. "${PGCFG_FILE}"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file sourcing <${PGCFG_FILE}> error; exiting !!!"
  exit 10
fi

CUST_CTX="$(mlget_cust_ctx 'cust')"
MOD_CTX="$(mlget_cust_ctx  'mod')"
BATCH_WFL_ID=1                  # workflow/product id
BATCH_MODE="oper"
if [ ! -z ${BATCH_RUN_MODE} ]
then
  BATCH_MODE="${BATCH_RUN_MODE}"
fi
LOG_CTX="${BATCH_MODE}-${CUST_CTX}"


PGCFG_FILE="${MLPROD_HOME}/cust/${CUST_CTX}/config/${MOD_CTX}.rc"
if [ ! -f ${PGCFG_FILE} ]
then
  echo "${PGERR} : config file <${PGCFG_FILE}> not found; exiting !!!"
  exit 10
fi

. "${PGCFG_FILE}"


trap cleanup EXIT ERR TERM INT QUIT


function usage()
{
  mllogerr "Usage: $PGNAME MMDDYY_HHMMSS_XXXXXX WHERE XXXXXX is cust_id";
}

if [ $# -lt 1 ]
then
  usage;
  exit 10;
else
  if [ "${2}" == "-s" ]
  then
    skip=1
  else
    skip=0
  fi
fi

BATCH_WFL_ID=1                  # workflow/product id


BPARAMETER="${1}"

if [ -z ${BPARAMETER} ]
then
  usage
  exit 10
fi


# LOG
LOG_CTX="${LOG_CTX}-${BPARAMETER}"

# OVERWRITE THE ARCHIVE DIRECTORIES to archive/recon/in AND archive/recon/backup
ARCH_CTX_BAK_DIR="${MLARCH_DIR}/recon/backup"


# files needed for restore cust context tables as of a batch
# batch_status_recon_t, recon_t
# BACKUP FILES

RECON_BAK_FILE=${ARCH_CTX_BAK_DIR}/${BPARAMETER}_recon_t.txt
BATCH_STATUS_BAK_FILE=${ARCH_CTX_BAK_DIR}/${BPARAMETER}_batch_status_recon_t.txt



if [ ! -r ${RECON_BAK_FILE} ]
then
  mllogerr "[${LOG_CTX}] : ERR : recon_t backup file not found : ${RECON_BAK_FILE}";
  exit 10;
fi

if [ ! -r ${BATCH_STATUS_BAK_FILE} ]
then
  mllogerr "[${LOG_CTX}] : ERR : batch_status_recon_t  backup file not found : ${BATCH_STATUS_BAK_FILE}";
  exit 10;
fi




TASK_ID=0
tstart=$((`date +%s`))

tstamp="00:00:00"
mllogerr "[${LOG_CTX}] : BEG : [${tstamp}] : RESTORE START"



TASK_ID=`expr $TASK_ID + 1`
tmsg="restore recon table";
mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
ts=$((`date +%s`))
   cat ${RECON_BAK_FILE} | ${PGSQL} ${SQL_CTX_REST_DIR}/restore_table_recon.sql
if [ $? -ne 0 ] 
then
  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  cleanup;
  exit -1;
fi
te=$((`date +%s`))


TASK_ID=`expr $TASK_ID + 1`
tmsg="restore batch status recon table";
mllogerr "[${LOG_CTX}] : INF : TASK-${TASK_ID} $tmsg";
ts=$((`date +%s`))
   cat ${BATCH_STATUS_BAK_FILE} | ${PGSQL} ${SQL_CTX_REST_DIR}/restore_table_batch_status_recon.sql
if [ $? -ne 0 ] 
then
  mllogerr "[${LOG_CTX}] : ERR : TASK-${TASK_ID} failed to ${tmsg}";
  cleanup;
  exit -1;
fi
te=$((`date +%s`))

tstamp="$(mltstamp ${tstart})"
mllogerr "[${LOG_CTX}] : END : [${tstamp}] : RESTORE DONE"

exit 0;
